package com.zj.leetcode.medium.tree;

import java.util.*;

/**
 * @program: algorithm
 * @description: 二叉树的锯齿形层序遍历
 * 103 binary-tree-zigzag-level-order-traversal
 * @author: Zhang Bo
 * @create: 2022-06-16 10:21:00
 **/
public class BinaryTreeZigzagLevelOrderTraversal {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeZigzagLevelOrderTraversal().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) {
                return res;
            }

            Deque<TreeNode> deque = new LinkedList<>();

            deque.add(root);
            boolean fromLeft = true;
            while (!deque.isEmpty()) {
                int size = deque.size();
                List<Integer> list = new LinkedList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode poll = null;
                    if (fromLeft) {
                        poll = deque.pollFirst();
                        if (poll != null) {
                            list.add(poll.val);
                        }
                        deque.addLast(poll);
                    } else {
                        poll = deque.pollLast();
                        if (poll != null) {
                            list.add(poll.val);
                        }
                        deque.addFirst(poll);
                    }

                }

                for (int i = 0; i < size; i++) {
                    TreeNode poll = deque.poll();
                    if(poll != null){
                        if(poll.left != null){
                            deque.addLast(poll.left);
                        }
                        if(poll.right != null){
                            deque.addLast(poll.right);
                        }
                    }
                }
                fromLeft = !fromLeft;
                res.add(list);
            }
            return res;
        }


    }
//leetcode submit region end(Prohibit modification and deletion)

}
